<template>
  <div class="main-container" v-loading="isLoading" :element-loading-text="loadingText">
    <div class="table-container">
      <div class="table-toolbar">
        <div>
          <el-tooltip effect="dark" content="刷新" placement="top">
            <el-button :icon="Refresh" @click="updateProjectsAsync()">刷新项目列表</el-button>
          </el-tooltip>
        </div>
        <div>
          <el-button type="primary" :icon="CirclePlusFilled" @click="showAddItemDialog = true"
            >新增</el-button
          >
        </div>
      </div>
      <el-divider />
      <el-scrollbar style="margin-top: 10px">
        <el-table :data="projects" style="width: 100%">
          <el-table-column fixed prop="projectName" label="项目名称" />
          <el-table-column fixed prop="site" label="基地编号" />
          <el-table-column fixed prop="creatorId" label="创建者" />
          <el-table-column prop="creationTime" label="创建时间" />
          <el-table-column prop="lastModifierId" label="编辑者" />
          <el-table-column prop="lastModificationTime" label="编辑时间" />
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="deleteProjectAsync(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
      <el-dialog
        v-model="showAddItemDialog"
        title="添加新设备配置"
        width="400"
        :close-on-click-modal="false"
        draggable
        :before-close="onDialogBeforeClose"
      >
        <div
          class="content-container"
          v-loading="dialogIsLoading"
          element-loading-text="正在添加新项目..."
        >
          <div style="margin-top: 20px">
            <div style="margin-top: 10px">
              <el-text>设备保养项目名称：</el-text>
              <el-input
                style="margin-top: 4px"
                maxlength="20"
                type="text"
                placeholder="请输入项目名称"
                v-model="projectName"
              ></el-input>
            </div>
            <div style="margin-top: 10px">
              <el-text>基地站点编号</el-text>
              <el-input
                style="margin-top: 4px"
                maxlength="20"
                type="number"
                placeholder="请输入基地站点编号"
                v-model="site"
              ></el-input>
            </div>
            <div style="margin-top: 20px; display: flex; justify-content: center">
              <el-button type="primary" @click="onInsertProjectAsync">添加</el-button>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
  
  <script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { CirclePlusFilled } from '@element-plus/icons-vue';
import { Refresh } from '@element-plus/icons-vue';
import type { ProjectInfo } from '@/types/ProjectInfo';
import { Project } from './Project';
import { sleepAsync } from '@/utils/test-api';
import { showDeleteMessageBoxAsync } from '@/utils/message-box';

const pageIndex = ref(0);
const pageSize = 50;
const project = new Project();
const projects = ref<ProjectInfo[]>([]);
const isLoading = ref(false);
const showAddItemDialog = ref(false);
const projectName = ref('');
const site = ref<number | null>(null);

function resetProps() {
  projectName.value = '';
  site.value = null;
}

const dialogIsLoading = ref(false);
const loadingText = ref('正在加载项目列表...');

function onDialogBeforeClose(done: any) {
  if (dialogIsLoading.value) {
    ElMessage.info('正在添加新的项目...');
  }
  // 对话框正在加载时，不关闭对话框
  done(dialogIsLoading.value);
}

function openDialogLoading() {
  dialogIsLoading.value = true;
}

function closeDialogLoading() {
  dialogIsLoading.value = false;
}

function openLoading() {
  // 如果对话框 loading 了，则不加载页面 loading
  if (!dialogIsLoading.value) isLoading.value = true;
}

function closeLoading() {
  isLoading.value = false;
}

async function updateProjectsAsync() {
  loadingText.value = '正在加载项目列表...';
  try {
    openLoading();
    await sleepAsync(500);
    projects.value = await project.getAsync(pageIndex.value * pageSize, pageSize);
  } catch (err) {
    const message = err as string;
    if (message != null) {
      ElMessage.warning(message);
    } else {
      console.error(err);
      ElMessage.error('获取项目列表错误！');
    }
  } finally {
    closeLoading();
  }
}

onMounted(async () => {
  await updateProjectsAsync();
});

async function onInsertProjectAsync() {
  if (site.value == null) {
    ElMessage.error('请输入站点！');
  } else if (projectName.value == '' || projectName.value == null || projectName.value.length < 6) {
    ElMessage.error('项目名称长度必须大于6个字符');
  } else {
    const projectInfo: ProjectInfo = {
      projectName: projectName.value,
      site: site.value,
      id: '',
      creationTime: '',
      lastModificationTime: '',
      creatorId: '',
      lastModifierId: ''
    };
    openDialogLoading();
    await sleepAsync(500);
    try {
      await project.insertAsync(projectInfo);
      await updateProjectsAsync();
      resetProps();
      showAddItemDialog.value = false;
    } catch (err) {
      const message = err as string;
      if (message != null) {
        ElMessage.warning(message);
      } else {
        console.error(err);
        ElMessage.error('添加新项目出现错误错误！');
      }
    } finally {
      closeDialogLoading();
    }
  }
}

async function deleteProjectAsync(index: number) {
  loadingText.value = '正在删除项目...';
  if (!(await showDeleteMessageBoxAsync())) {
    return;
  }
  openLoading();
  const projectItem = projects.value[index];
  try {
    await project.deleteAsync(projectItem.id);
    await updateProjectsAsync();
  } catch (err) {
    const message = err as string;
    if (message != null) {
      ElMessage.warning(message);
    } else {
      console.error(err);
      ElMessage.error('删除项目错误！');
    }
  } finally {
    closeLoading();
  }
}
</script>
  
  <style lang="scss" scoped>
:deep(.el-divider--horizontal) {
  margin: 15px 0px 0px 0px;
}
.main-container {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .table-container {
    margin: 0px 15px 15px 15px;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}

.collapse-title-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.columns-setting-icon {
  display: block;
  font-size: 18px;
  cursor: pointer;
  color: #676767;
}

.table-header .cell {
  color: #333;
}

.content-container {
  height: 100%;
  width: 100%;
  flex-direction: column;
  justify-content: center;
  display: flex;
  align-items: center;
  background-color: #fff;
}
</style>
  